package org.acghub.mtdb.test;

import java.util.concurrent.TimeUnit;

public class InterruptExample {

    public static void main(String[] args) {
        Thread worker = new Thread(() -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("Worker is running...");
                    // 模拟工作 阻塞操作
                    TimeUnit.SECONDS.sleep(60);
                }
            } catch (InterruptedException e) {
                // 重新设置中断标志（保留中断状态）
                Thread.currentThread().interrupt();
                System.out.println("Worker thread was interrupted, cleaning up resources...");
            } finally {
                // 清理资源
                cleanup();
            }
            System.out.println("Worker thread is exiting.");
        });

        worker.start();

        // 主线程等待一段时间后中断 worker 线程
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        worker.interrupt(); // 发起中断请求

        try {
            worker.join(); // 等待 worker 线程结束
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void cleanup() {
        System.out.println("Cleaning up resources...");
        // 关闭文件、网络连接等
    }
}
